package com.huibao.hulibao.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
//import android.os;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.smartdevice.aidl.IZKCService;

import java.io.File;
import java.io.UnsupportedEncodingException;

import common.MessageType;
import pdautils.PdaPrint;

/**
 * 展示WebView中的详细内容
 *
 * @author Administrator
 */
public class WebViewActivity extends BaseActivity {
    public ImageView iv_back;
    public WebView wb_detail;
    public TextView tv_title;
    public RelativeLayout rl_base_title;
    protected static final String APP_CACHE_DIRNAME = "/cache_path";
    private String url;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_webview_detail);

        initView();
        initData();
        // bindService();
    }

    // @Override
    @Override
    public void onBackPressed() {
        if (wb_detail.canGoBack()) {
            wb_detail.goBack();// 返回前一个页面
        } else {
            finish();
        }
    }

    public class JavaScriptinterface {

        private Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        public JavaScriptinterface(Context c) {
            mContext = c;
        }

        // 给JS调用的升级方法
        @JavascriptInterface
        public void updateApp(String path) {
            // https://www.pgyer.com/hpda2
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(path);
            intent.setData(content_url);
            startActivity(intent);

//            Intent intent_update = new Intent(
//                    Intent.ACTION_VIEW,
//                    Uri.parse(path));
//            startActivity(intent_update);
        }

        // 关闭webview
        @JavascriptInterface
        public void closeWeb() {
            finish();
        }


        //@SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void pdaPrint(String msg) {
            pdautils.PdaPrint.printMsg(msg, getApplicationContext());
        }
    }

//    public void bindService() {
//        //com.zkc.aidl.all为远程服务的名称，不可更改
//        //com.smartdevice.aidl为远程服务声明所在的包名，不可更改，
//        // 对应的项目所导入的AIDL文件也应该在该包名下
//        Intent intent = new Intent("com.zkc.aidl.all");
//        intent.setPackage("com.smartdevice.aidl");
//        bindService(intent, PdaPrint.getInstance().mServiceConn, Context.BIND_AUTO_CREATE);
//    }
//
//    public void unbindService() {
//        unbindService(PdaPrint.getInstance().mServiceConn);
//    }

    @Override
    protected void onStop() {
        //PdaPrint.getInstance().onStop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
//        try {
//            unbindService();
//        }catch (IllegalArgumentException e){
//            e.printStackTrace();
//        }
        super.onDestroy();
    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @JavascriptInterface
    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        wb_detail = (WebView) findViewById(R.id.wv_detail);
        rl_base_title = (RelativeLayout) findViewById(R.id.rl_base_title);
        iv_back = (ImageView) findViewById(R.id.iv_back);


        // 不使用缓存：
        // webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // webSettings.setJavaScriptEnabled(true);
        initWebView();

        // 让JS调用Android的方法
        wb_detail.addJavascriptInterface(new JavaScriptinterface(this),
                "android");

        wb_detail.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d("url = " + url);
                if (url.contains(GlobalConstants.WEB_NAV) && !url.contains(GlobalConstants.WEB_NO_NAV)) {
                    // 显示导航栏
                    rl_base_title.setVisibility(View.VISIBLE);
                } else if (url.contains(GlobalConstants.WEB_NO_NAV)) {
                    // 不显示导航栏
                    rl_base_title.setVisibility(View.GONE);
                } else if (url.contains(GlobalConstants.WEN_CLOSE)) {
                    // 退出当前webview
                    finish();
                } else if (url.contains(GlobalConstants.WEN_lOGIN)) {
                    // 退出登录 去登录页面
                    PreUtils.saveObject(getApplicationContext(), "LoginEntity", null);
                    Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Toast.makeText(getApplicationContext(), R.string.wangluobuhao,
                        Toast.LENGTH_SHORT).show();
            }
        });
        wb_detail.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                result.confirm();
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message,
                                      String defaultValue, JsPromptResult result) {
                // TODO Auto-generated method stub
                return super.onJsPrompt(view, url, message, defaultValue,
                        result);
            }

            // 获取webview的title
            @Override
            public void onReceivedTitle(WebView view, String web_title) {
                super.onReceivedTitle(view, title);
                LogUtils.d("web_title = " + web_title);
                if (title != null) {
                    if (title.equals("")) {
                        tv_title.setText(web_title);
                    }
                } else {
                    if (web_title != null && !web_title.equals("")) {
                        tv_title.setText(web_title);
                    }
                }
            }

        });
        wb_detail.loadUrl(url);
    }

    public void initWebView() {
        wb_detail.getSettings().setJavaScriptEnabled(true);
        wb_detail.getSettings().setRenderPriority(RenderPriority.HIGH);
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        // 开启DOM storage API 功能
        wb_detail.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
        wb_detail.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath()
                + APP_CACHE_DIRNAME;
        // Log.i(TAG, cacheDirPath);
        // 设置数据库缓存路径
        wb_detail.getSettings().setDatabasePath(cacheDirPath); // API 19
        // deprecated
        // 设置Application caches缓存目录
        wb_detail.getSettings().setAppCachePath(cacheDirPath);
        // 开启Application Cache功能
        wb_detail.getSettings().setAppCacheEnabled(true);

        // Log.i(TAG, wb_detail.getSettings().getDatabasePath());
    }

    public void clearWebViewCache() {
        // 清理WebView缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // WebView缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath()
                + APP_CACHE_DIRNAME);
        // Log.e(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath()
                + "/webviewCache");
        // Log.e(TAG, "appCacheDir path=" + webviewCacheDir.getAbsolutePath());

        // 删除webView缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        // 删除webView缓存，缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    public void deleteFile(File file) {
        // Log.i(TAG, "delete file path=" + file.getAbsolutePath());
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
//			Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    private void initData() {
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        LogUtils.d("url = " + url);
        title = intent.getStringExtra("title");
        tv_title.setText(title);
        wb_detail.loadUrl(url);
        iv_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                // Log.i(TAG, "back");
            }
        });
    }
}
